package com.iplant.basic.controller.bms;

import com.iplant.base.controller.BaseController;
import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.po.excel.ExcelData;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.cache.CacheUtils;
import com.iplant.base.utils.excel.ExcelReader;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.orm.ORMUtils;
import com.iplant.base.utils.sql.orm.PoService;
import com.iplant.basic.service.BMSService;
import com.iplant.basic.service.po.bms.BMSClassInfo;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.serviceImpl.BMSServiceImpl;
import com.iplant.basic.serviceImpl.dao.bms.BMSEmployeeDAO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/BMSClassInfo")
public class BMSClassInfoController extends BaseController {

    PoService<BMSClassInfo> mPoService = ORMUtils.GetPoService(BMSClassInfo.class);

    @Autowired
    BMSService mBMSService;

    @GetMapping("/All")
    public Object All(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);
            Map<String, Object> wParams = GetParamsMap(request);
            Pagination wPagination = GetPagination(request);

            //渲染班组数据
            BMSServiceImpl.getInstance().InitClassInfo(wLoginUser);

            ServiceResult<List<BMSClassInfo>> wServiceResult = mPoService.SelectPOList(wLoginUser, wParams,
                    wPagination);

            //班组人数查询
            if (wServiceResult.Result.size() > 0) {
                Map<Integer, Integer> wDepartmentNumMap = mBMSService.BMS_QueryDepartmentNumMap(wLoginUser,
                        wServiceResult.Result.stream().map(p -> p.DepartmentID).collect(Collectors.toList()));

                for (BMSClassInfo wBMSClassInfo : wServiceResult.Result) {
                    if (wDepartmentNumMap.containsKey(wBMSClassInfo.DepartmentID)) {
                        wBMSClassInfo.MemberNumber = wDepartmentNumMap.get(wBMSClassInfo.DepartmentID);
                    }
                }
            }

            CacheUtils.SetData(wServiceResult.Result);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, wPagination.getTotalPage());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @GetMapping("/Info")
    public Object Info(HttpServletRequest request) {
        Object wResult = new Object();
        try {

            BMSEmployee wLoginUser = GetSession(request);

            Map<String, Object> wParams = GetParamsMap(request);
            ServiceResult<BMSClassInfo> wServiceResult = mPoService.SelectPO(wLoginUser, wParams);
            //翻译成员
            List<BMSClassInfo> wList = new ArrayList<>(Collections.singletonList(wServiceResult.Result));
            if (wServiceResult.Result.ID > 0 && wServiceResult.Result.DepartmentID > 0) {
                OutResult<Integer> wErrorCode = new OutResult<Integer>(0);
                wList.get(0).MemberList = BMSEmployeeDAO.getInstance().BMS_QueryEmployeeList(wLoginUser,
                        wList.get(0).DepartmentID, -1, -1, -1, 1, "", Pagination.getMaxSize(), wErrorCode);
                CacheUtils.SetData(wList);
            }

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wList.get(0));
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode(), null,
                        wServiceResult.getResult());
            }

        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/Update")
    public Object Update(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult = new Object();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);


            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            BMSClassInfo wBMSClassInfo = CloneTool.Clone(wParam.get("data"), BMSClassInfo.class);

            wBMSClassInfo.setUserInfo(wBMSEmployee);

            ServiceResult<Integer> wServiceResult = mPoService.UpdatePo(wBMSEmployee, wBMSClassInfo);

            List<BMSClassInfo> wList = new ArrayList<>(Collections.singletonList(wBMSClassInfo));
            CacheUtils.SetData(wList);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wList.get(0));
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/Active")
    public Object Active(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult = new Object();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            int wActive = wParam.containsKey("Active") ? (int) wParam.get("Active") : 0;

            List<BMSClassInfo> wBMSClassInfoList = CloneTool.CloneArray(wParam.get("data"), BMSClassInfo.class);
            ServiceResult<Integer> wServiceResult = new ServiceResult<Integer>(0);
            for (BMSClassInfo wBMSClassInfo : wBMSClassInfoList) {

                wServiceResult = mPoService.ActivePO(wBMSEmployee, wBMSClassInfo, wActive);

                if (!StringUtils.isEmpty(wServiceResult.getFaultCode()))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "");
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/Delete")
    public Object Delete(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult = new Object();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            BMSClassInfo wBMSClassInfo = CloneTool.Clone(wParam.get("data"), BMSClassInfo.class);

            ServiceResult<Integer> wServiceResult = mPoService.DeletePO(wBMSEmployee, wBMSClassInfo);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "");
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 导入
     */
    @PostMapping("/Import")
    public Object Import(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = mBMSService.BMS_ImportClassInfo(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", null, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 根据班组成员Excel导入用户
     */
    @PostMapping("/ImportUser")
    public Object ImportUser(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = mBMSService.BMS_ImportUserByClassInfo(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", null, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }
}
